import React, { forwardRef, useState, useRef, useEffect } from "react";
import { View, Textarea, ScrollView } from "@tarojs/components";
import {
  HeadIcon,
  ListIcon,
  NumberIcon,
  WarnBlockIcon,
} from "@/components/Icons";
import { getMdString } from "@/utils";
import Taro from "@tarojs/taro";
import BaseTrigger from "@/components/BaseTrigger";
import { usePopup } from "@/store/popup";
import "./index.less";
import Tabs from "@/components/Tabs";
import MdRenderer from "@/components/MdRenderer";
import { TValue } from "@/types";

interface DescriptionFormProps {
  value: string;
  onClose: () => void;
  onSave: (value: string) => void;
}

const MdText = forwardRef((props: DescriptionFormProps, ref) => {
  const [value, setValue] = useState(props.value);
  const [cursor, setCursor] = useState(0);
  const [action, setAction] = useState(false);
  const typeRef = useRef("");
  const textRef = React.useRef<HTMLTextAreaElement>(null);
  const [keyboardHeight, setHeight] = useState(0);
  const [mode, setMode] = useState<TValue>("edit");

  const [selection, setSelection] = useState({ start: 0, end: 0 });
  const focusAtPosition = (start, end = start) => {
    setSelection({ start, end });

    const timer = setTimeout(() => {
      if (textRef.current) {
        textRef.current.focus();
      }
      clearTimeout(timer);
    }, 100);
  };
  const beforeInsert = (type) => {
    if (!textRef.current) return;
    textRef.current.blur();
    typeRef.current = type;
  };

  useEffect(() => {
    if (typeRef.current !== "") {
      const [str, pos] = getMdString(typeRef.current, value, cursor);
      setValue(str);
      focusAtPosition(pos);
      typeRef.current = "";
    }
  }, [cursor, action]);

  return (
    <View className="mdeditor">
      <View className="md-header flex-between">
        <View>
          <Tabs
            options={[
              { label: "编辑", value: "edit" },
              { label: "预览", value: "preview" },
            ]}
            value={mode}
            onChange={(value) => setMode(value)}
          />
        </View>
        <View
          className="flex-align"
          onClick={() => {
            props?.onSave(value);
          }}
        >
          保存
        </View>
      </View>
      {mode === "edit" ? (
        <View
          style={{
            position: "fixed",
            top: Taro.pxTransform(60),
            bottom: keyboardHeight || 0,
            width: "100%",
          }}
        >
          <ScrollView scrollY className="md-body">
            <Textarea
              ref={textRef}
              value={value}
              maxlength={800}
              autoFocus
              selectionStart={selection.start}
              selectionEnd={selection.end}
              onInput={(e) => {
                setCursor(e.detail.cursor);
                setValue(e.detail.value);
              }}
              holdKeyboard={true}
              onBlur={(e) => {
                setCursor(e.detail.cursor);
                setAction(!action);
              }}
              showConfirmBar={false}
              onKeyboardHeightChange={(e) => {
                if (e.detail.height === 0 || e.detail.height > 50) {
                  setHeight(e.detail.height);
                }
              }}
            />
          </ScrollView>

          <View className="md-toolbar">
            <HeadIcon
              type="default"
              size={1.6}
              onClick={() => beforeInsert("head")}
            />
            <ListIcon
              size={1.5}
              type="default"
              onClick={() => beforeInsert("list")}
            />
            <NumberIcon
              type="default"
              size={1.5}
              onClick={() => beforeInsert("number")}
            />
            <WarnBlockIcon
              type="default"
              size={1.5}
              onClick={() => beforeInsert("code")}
            />
          </View>
        </View>
      ) : (
        <ScrollView scrollY style={{ height: "90%" }}>
          <MdRenderer
            content={value}
            style={{ padding: Taro.pxTransform(36) }}
          />
        </ScrollView>
      )}
    </View>
  );
});

const MdTrigger = ({ label = "描述", value, onChange }) => {
  const { openPopup, closePopup } = usePopup();
  const ref = useRef(null);
  return (
    <BaseTrigger
      label={label}
      onClick={() => {
        openPopup({
          showConfirm: false,
          round: false,
          getNode: () => (
            <MdText
              ref={ref}
              value={value}
              onClose={closePopup}
              onSave={(value) => {
                onChange(value);
                closePopup();
              }}
            />
          ),
        });
      }}
    />
  );
};

export default MdTrigger;
